class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0

        def search(node):
            left_length = 0
            right_length = 0
            max_value1 = 0
            max_value2 = 0
            if node.left:
                left_length, max_value1 = search(node.left)
            if node.right:
                right_length, max_value2 = search(node.right)
            max_length = max(left_length, right_length) + 1
            max_value = max(left_length + right_length + 1, max_value1, max_value2)
            return max_length, max_value

        return search(root)[1] - 1
